from code import interact
import numpy as np
from scipy.spatial.distance import directed_hausdorff

def dice_coefficient(y_true, y_pred):
    smooth = 1e-6
    y_true_f = y_true.flatten()
    y_pred_f = y_pred.flatten()
    intersection = (y_true_f * y_pred_f).sum()
    return (2. * intersection + smooth) / (y_true_f.sum() + y_pred_f.sum() + smooth)

def calculate_hd95(y_true, y_pred):
    y_true = np.where(y_true == 1)
    y_pred = np.where(y_pred == 1)
    y_true = np.array([y_true[0], y_true[1]]).T
    y_pred = np.array([y_pred[0], y_pred[1]]).T

    forward_hd = max(directed_hausdorff(y_true, y_pred)[0], directed_hausdorff(y_pred, y_true)[0])
    hd95 = np.percentile(forward_hd, 95)

    return hd95

def iou(y_true, y_pred):
    intersection = np.logical_and(y_true, y_pred)
    union = np.logical_or(y_true, y_pred)
    iou_score = np.sum(intersection) / np.sum(union)
    return iou_score

def accuracy(y_true, y_pred):
    y_pred = np.round(y_pred)  # 将 y_pred 四舍五入到最近的整数

    TP = np.sum((y_true == 1) & (y_pred == 1))  # 计算真正例
    TN = np.sum((y_true == 0) & (y_pred == 0))  # 计算真负例
    FP = np.sum((y_true == 0) & (y_pred == 1))  # 计算假正例
    FN = np.sum((y_true == 1) & (y_pred == 0))  # 计算假负例

    return (TP + TN) / (TP + FN + FP + TN)  # 计算精确度

def precision(y_true, y_pred):
    y_pred = np.round(y_pred)
    
    TP = np.sum((y_true == 1) & (y_pred == 1))  # 计算真正例
    FP = np.sum((y_true == 0) & (y_pred == 1))  # 计算假正例
    
    return TP / (TP + FP)  # 计算精确度

def recall(y_true, y_pred):
    y_pred = np.round(y_pred)
    
    TP = np.sum((y_true == 1) & (y_pred == 1))  # 计算真正例
    FN = np.sum((y_true == 1) & (y_pred == 0))  # 计算假负例
    
    return TP / (TP + FN)  # 计算精确度